package com.lxujia.ruankao.adapter;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.view.PagerAdapter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lxujia.ruankao.R;
import com.lxujia.ruankao.activity.QuestionItemActivity;
import com.lxujia.ruankao.model.QuestionAnswerItem;
import com.lxujia.ruankao.model.QuestionItem;
import com.lxujia.ruankao.ui.AnswerDetailView;
import com.lxujia.ruankao.util.LogUtil;
import com.lxujia.ruankao.util.ConstantUtil;

import org.litepal.LitePal;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class QuestionPagerAdapter extends PagerAdapter {
    public final static String TAG = "QuestionPagerAdapter";
    private Context mContext;
    private String mHeaderText;
    private Integer[] mAnswerIcons = new Integer[]{
            R.drawable.ic_a_1,
            R.drawable.ic_b_1,
            R.drawable.ic_c_1,
            R.drawable.ic_d_1 };
    private int RIGHT_ICON = R.drawable.ic_right_1;
    private int ERROR_ICON = R.drawable.ic_error_1;

    private List<QuestionAnswerItem> mAnswerList = null;
    private List<QuestionItem> mList;
    private QuestionItemActivity.ViewPagerNextListener mCallback;

    public QuestionPagerAdapter(Context context, String headerText) {
        mContext = context;
        mHeaderText = headerText;
    }

    public void setData(List<QuestionItem> questionItems) {
        this.mList = questionItems;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = initView(position);
        container.addView(view);
        return view;
    }

    // 解决 notifyDataSetChanged 不刷新问题
    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    private View initView(int position) {
        View questionContainerView = View.inflate(mContext,
                R.layout.activity_question_detail_question_container, null);

        //设置header start
        TextView headerView = (TextView) questionContainerView.findViewById(R.id.question_common_header_content);
        headerView.setText(mHeaderText);
        //设置header end

        initUI(questionContainerView, mList.get(position));

        //设置footer start
        TextView footerView = (TextView) questionContainerView.findViewById(R.id.question_common_footer_content);
        footerView.setText((position + 1) + "/" + (getCount()));
        //设置footer end

        return questionContainerView;
    }

    /**
     *
     * @param questionContainerView
     * @param questionItem
     */
    private void initUI(View questionContainerView, QuestionItem questionItem) {
        LogUtil.d(TAG, "questionItem = " + questionItem);

        initQuestTitle(questionContainerView, questionItem);

        initQuestAnswerAnalysis(questionContainerView, questionItem);

        initAnserList(questionContainerView, questionItem);
    }

    /**
     * 初始化问题题目
     */
    private void initQuestTitle(View container, QuestionItem questionItem) {
        TextView questionTitleTv = (TextView) container.findViewById(R.id.question_title_tv);//试题标题
        ImageView illustrationIv = (ImageView) container.findViewById(R.id.question_illustration_iv);//问题插图

        String questionTitle = questionItem.getQuestionTitle();//问题题干
        String illustration = questionItem.getQuestionImage();//问题插图

        questionTitleTv.setText(questionTitle);
        Bitmap questionBitmap = getAssetsImage(illustration);
        if (questionBitmap != null) {
            illustrationIv.setVisibility(View.VISIBLE);
            illustrationIv.setImageBitmap(questionBitmap);
        } else {
            illustrationIv.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化问题答案详解
     */
    private void initQuestAnswerAnalysis(View container, QuestionItem questionItem) {
        TextView questionAnswerAnalysisTv = (TextView) container.findViewById(R.id.question_answer_analysis_tv);//试题详解内容
        ImageView questionAnswerAnalysisIv = (ImageView) container.findViewById(R.id.question_answer_analysis_iv);//试题详解内容 img

        String questionDesc = questionItem.getAnswerDesc(); //问题详解描述
        String descIllustration = questionItem.getAnswerDescImage();//问题详解描述 img

        questionAnswerAnalysisTv.setText(questionDesc);
        Bitmap answerDescBitmap = getAssetsImage(descIllustration);
        if (answerDescBitmap != null) {
            questionAnswerAnalysisIv.setVisibility(View.VISIBLE);
            questionAnswerAnalysisIv.setImageBitmap(answerDescBitmap);
        } else {
            questionAnswerAnalysisIv.setVisibility(View.GONE);
        }
        // 默认隐藏
        setAnswerAnalysisVisibility(container, false);
    }

    /**
     * 问题选项 view 显示
     */
    private void initAnswerDetaiView(QuestionAnswerItem item, AnswerDetailView answerDetailView) {
        ImageView answerIconIv = (ImageView) answerDetailView.findViewById(R.id.answer_ic_iv);
        TextView answerTextTv = (TextView) answerDetailView.findViewById(R.id.answer_text_tv);

        answerTextTv.setText(item.getAnswerText());
        answerIconIv.setImageResource(item.getAnswerIcon());
    }


    /**
     * 初始化 问题选项
     * @param container
     * @param questionItem
     */
    private void initAnserList(final View container, final QuestionItem questionItem) {
        final Map<Integer, AnswerDetailView> answerDetailViewMap = new LinkedHashMap<>();

        int userAnswer = questionItem.getUserAnswer(); //用户答案： 0 A，1 B，2 C，3 D，-1 未做题
        final int rightAnswer = getRightAnswerInt(questionItem.getRightAnswer()); // 正确答案
        final int questionId = questionItem.getId();

        if (mAnswerList != null) {
            mAnswerList.clear();
        }
        mAnswerList = getAnswerListData(questionItem);

        LinearLayout answerListView = (LinearLayout) container.findViewById(R.id.question_answer_list_container);
        for(int i = 0; i < mAnswerList.size(); i++) {
            AnswerDetailView answerDetailView = (AnswerDetailView) View.inflate(mContext,
                    R.layout.activity_question_answer_list, null);
            QuestionAnswerItem item = mAnswerList.get(i);
            initAnswerDetaiView(item, answerDetailView);

            answerDetailView.setAnswerId(i);

            if (userAnswer == -1) {// 此题用户未做，则添加 onclick 事件，使用户可以点击
                answerDetailView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int answerId = -1;
                        if (view instanceof AnswerDetailView) {
                            answerId = ((AnswerDetailView) view).getAnswerId();
                        }
                        if (answerId == -1) {
                            return;
                        }

                        LogUtil.d(TAG, "onClick answerId = " + answerId);

                        // 用户选择了某一选项，更新数据库
                        updateQuestionItem(questionId, rightAnswer, answerId);

                        // 更新数据，设置当前被选择
                        updateAnswerList(rightAnswer, answerId, answerDetailViewMap);

                        nextItem(rightAnswer == answerId);

                        setAnswerAnalysisVisibility(container, true);
                    }
                });
            }
            answerDetailViewMap.put(i, answerDetailView);
            answerListView.addView(answerDetailView);
        }

        // 当前题目用户已经选择了选项，取消item点击事件。并且显示答案解析
        if (userAnswer != -1) {
            setAnswerAnalysisVisibility(container, true);
        }
    }

    private void nextItem(boolean isRight) {
       // mViewPager.setCurrentItem(getCurrentItem() + 1);//跳转下一页
        if (mCallback != null) {
            mCallback.GotoNextItem(isRight);
        }
    }

    /**
     * 用户点击选项后，更新 mAnswerList，并且更新ui
     *
     */
    private void updateAnswerList(int rightAnswer, int userAnswer,
                                  Map<Integer, AnswerDetailView> answerDetailViewMap) {
        if (userAnswer != -1) { // 用户已经做了此题
            // 正确答案的选项图标为 RIGHT_ICON
            mAnswerList.get(rightAnswer).setAnswerIcon(RIGHT_ICON);
            ImageView rightAnserIcon = (ImageView) answerDetailViewMap.get(rightAnswer).
                    findViewById(R.id.answer_ic_iv);
            rightAnserIcon.setImageResource(RIGHT_ICON);

            if (rightAnswer != userAnswer) {// 用户答案是错误答案
                // 用户选择的错误答案错误答案的选项图标为 ERROR_ICON
                mAnswerList.get(userAnswer).setAnswerIcon(ERROR_ICON);
                ImageView errorAnserIcon = (ImageView) answerDetailViewMap.get(userAnswer).
                        findViewById(R.id.answer_ic_iv);
                errorAnserIcon.setImageResource(ERROR_ICON);
            }
        }
        for (int i = 0; i < mAnswerList.size(); i++) {
            answerDetailViewMap.get(i).setOnClickListener(null);
        }
    }

    /**
     * 设置问题答案详解是否显示
     */
    private void setAnswerAnalysisVisibility(View container, boolean visibility) {
        LinearLayout questionAnswerAnalysisLayout = (LinearLayout) container.findViewById(R.id.question_answer_analysis_ll);//试题详解Layout

        questionAnswerAnalysisLayout.setVisibility(visibility ? View.VISIBLE : View.GONE);
    }


    private void updateQuestionItem(int questionId, int rightAnswer, int userAnswer) {
        QuestionItem questionItem = LitePal.find(QuestionItem.class, questionId);
        int i = questionItem.getNo() - 1;
        questionItem.setUserAnswer(userAnswer);
        mList.get(i).setUserAnswer(userAnswer);
        if (rightAnswer != userAnswer) {//用户答案错误
            questionItem.setIsError(1);
            mList.get(i).setIsError(1);
        }
        questionItem.save();

    }

    private Bitmap getAssetsImage(String image) {
        LogUtil.d(TAG, "getAssetsImage image = " + image);
        if (TextUtils.isEmpty(image)) {
            return null;
        }
        if (image.contains(ConstantUtil.STRING_LIST_SPLIT)) {
            String[] imageFiles = image.split(ConstantUtil.STRING_LIST_SPLIT);
            for(String imageFile : imageFiles) {
                LogUtil.d(TAG, "getAssetsImage imageFile = " + imageFile);
                return getImageFromAssets(imageFile);
            }
        }

        return getImageFromAssets(image);
    }

    /**
     * 从Assets目录下获取图片方法
     *
     * @param imageName
     * @return Bitmap
     */
    public Bitmap getImageFromAssets(String imageName) {
        Bitmap bitmap = null;
        AssetManager am = mContext.getAssets();
        InputStream is = null;
        try {
            is = am.open(imageName);//得到图片流
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (is != null) {
            bitmap = BitmapFactory.decodeStream(is);
        }
        return bitmap;
    }

    private int getRightAnswerInt (String rightAnswer) {
        if ("A".equalsIgnoreCase(rightAnswer)) {
            return 0;
        }
        if ("B".equalsIgnoreCase(rightAnswer)) {
            return 1;
        }
        if ("C".equalsIgnoreCase(rightAnswer)) {
            return 2;
        }
        if ("D".equalsIgnoreCase(rightAnswer)) {
            return 3;
        }
        return -1;
    }

    /**
     * 获取问题选项 data，用于展示
     */
    private List<QuestionAnswerItem> getAnswerListData(QuestionItem questionItem) {
        List<QuestionAnswerItem> answerItemList = new ArrayList<QuestionAnswerItem>(){};

        String[] answers = getSplitString(questionItem.getAnswerList());//答案列表
        //String[] answerIllustrations = getSplitString(questionItem.getAnswerListImage());//答案插图
        int rightAnswer = getRightAnswerInt(questionItem.getRightAnswer());//问题正确答案
        int userAnswer = questionItem.getUserAnswer(); //用户答案： 0 A，1 B，2 C，3 D，-1 未做题
        boolean isRightAnswer = false;
        boolean isUserAnswer = false;

        for (int i = 0; i < answers.length; i++) {
            isRightAnswer = (i == rightAnswer);
            isUserAnswer = (i == userAnswer);
            answerItemList.add(new QuestionAnswerItem(answers[i], mAnswerIcons[i],
                    isRightAnswer, isUserAnswer));
        }

        if (userAnswer != -1) { // 用户已经做了此题
            // 正确答案的选项图标为 RIGHT_ICON
            answerItemList.get(rightAnswer).setAnswerIcon(RIGHT_ICON);
            if (rightAnswer != userAnswer) {// 用户答案是错误答案
                // 用户选择的错误答案错误答案的选项图标为 ERROR_ICON
                answerItemList.get(userAnswer).setAnswerIcon(ERROR_ICON);
            }
        }

        return answerItemList;
    }

    private String[] getSplitString(String string) {
        LogUtil.d(TAG, "getSplitString = " + string);
        if (TextUtils.isEmpty(string)) {
            return null;
        }
        return string.split(ConstantUtil.STRING_LIST_SPLIT);
    }

    public void setGotoNexCallback(QuestionItemActivity.ViewPagerNextListener goToNextPager) {
        this.mCallback = goToNextPager;
    }
}
